package com.bianguo.android.pigeondemo.model;

import android.os.Environment;

import com.bianguo.android.pigeondemo.retrofit.ApiService;
import com.bianguo.android.pigeondemo.retrofit.cache.ApiCache;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.rx_cache2.internal.RxCache;
import io.victoralbertos.jolyglot.GsonSpeaker;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/6/4.
 */

public class ModelFactory {

    public static final String CACHE_DIR = Environment.getExternalStorageDirectory().getPath() + "/PigeonDemo/temp/";
    public static final String BASE_URL = "https://api.douban.com/v2/movie/";
    public static final int MODEL_TYPE_MAIN = 0x1001;
    private static final int TIME_OUT_READ = 15;
    private static final int TIME_OUT_CONNECTION = 10;
    private static volatile ModelFactory mFactory;
    protected ApiService apiService;
    protected ApiCache apiCache;

    private ModelFactory() {

        File file = new File(CACHE_DIR);
        Cache mCache = new Cache(file, 20 * 1024 * 1024);
        OkHttpClient mClient = new OkHttpClient.Builder()
                .cache(mCache)
                .connectTimeout(TIME_OUT_CONNECTION, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT_READ, TimeUnit.SECONDS)
                .build();

        Retrofit mRetrofit = new Retrofit.Builder()
                .client(mClient)
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

        apiCache = new RxCache.Builder()
                .persistence(new File(CACHE_DIR), new GsonSpeaker())
                .using(ApiCache.class);

        apiService = mRetrofit.create(ApiService.class);
    }

    public static ModelFactory getInstance() {
        ModelFactory modelFactory = mFactory;
        if (modelFactory == null) {
            synchronized (ModelFactory.class) {
                if (modelFactory == null) {
                    modelFactory = new ModelFactory();
                    mFactory = modelFactory;
                }
            }
        }
        return modelFactory;
    }

    public BaseModel createModel(int modelType) {
        switch (modelType) {
            case MODEL_TYPE_MAIN:
                return new MainModel();
        }
        return null;
    }
}
